<?php

namespace App\Lib;

class SnsapiLogin
{
    const APP_ID = 'wx2d92665e225a76ca';
    const SECRET = '7443bfdc379a403edc6de040d2e747e1';

    public static function getLoginUrl($url = '')
    {
        if (!$url)
            $url = 'https://www.henjiyn.com/';
        $redirect_url = urlencode($url);
        $url = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx2d92665e225a76ca&redirect_uri=' . $redirect_url . '&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect';
        return $url;
    }

    public static function getUserInfo($code)
    {
        $appid = self::APP_ID;
        $secret = self::SECRET;

        //第一步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = self::getJson($oauth2Url);
        \Log::info(var_export($oauth2, true));
        if (!empty($oauth2['errcode'])) {
            throw new \Exception($oauth2['errmsg']);
        }
        //第二步:根据全局access_token和openid查询用户信息
        $access_token = $oauth2["access_token"];
        $openid = $oauth2['openid'];
        $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo = self::getJson($get_user_info_url);
        return $userinfo;
    }

    private static function getJson($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

}
